package cn.edu.tju.core.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUploadUtil {
    
    // 默认允许的文件类型
    private static final String[] ALLOWED_IMAGE_EXTENSIONS = {"jpg", "jpeg", "png", "gif", "webp"};
    
    /**
     * 上传文件到指定目录
     * 
     * @param file 上传的文件
     * @param uploadDir 上传目录路径
     * @param allowedExtensions 允许的文件扩展名
     * @return 文件在服务器上的相对路径
     * @throws IOException 文件操作异常
     * @throws IllegalArgumentException 文件类型不允许或其他参数错误
     */
    public static String saveFile(MultipartFile file, String uploadDir, String[] allowedExtensions) throws IOException, IllegalArgumentException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        
        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        
        // 检查文件类型是否允许
        boolean isAllowed = false;
        for (String allowedExtension : allowedExtensions) {
            if (allowedExtension.equalsIgnoreCase(extension)) {
                isAllowed = true;
                break;
            }
        }
        
        if (!isAllowed) {
            throw new IllegalArgumentException("不支持的文件类型");
        }
        
        // 生成唯一文件名，避免文件覆盖
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String uniqueFileName = UUID.randomUUID().toString().substring(0, 8) + "_" + timestamp + "." + extension;
        
        // 创建目标目录
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 保存文件到目标位置
        Path filePath = uploadPath.resolve(uniqueFileName);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        
        // 返回相对路径
        return uniqueFileName;
    }
    
    /**
     * 上传图片文件
     * 
     * @param file 上传的文件
     * @param uploadDir 上传目录路径
     * @return 文件在服务器上的相对路径
     * @throws IOException 文件操作异常
     * @throws IllegalArgumentException 文件类型不允许或其他参数错误
     */
    public static String saveImage(MultipartFile file, String uploadDir) throws IOException, IllegalArgumentException {
        return saveFile(file, uploadDir, ALLOWED_IMAGE_EXTENSIONS);
    }
    
    /**
     * 删除文件
     * 
     * @param filePath 文件的完整路径
     * @return 是否删除成功
     */
    public static boolean deleteFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            return Files.deleteIfExists(path);
        } catch (IOException e) {
            return false;
        }
    }
} 